<template>
  <BaseChatMsg :avatar="avatar" :align="align">
    <template v-slot:chat>
      <div class="image-wrapper">
        <van-image class="image" radius="8" lazy-load :src="url" @load="loadImage" ref="image">
          <template v-slot:loading>
            <van-loading type="spinner" size="20" />
          </template>
        </van-image>
      </div>
    </template>
  </BaseChatMsg>
</template>

<script>
import BaseChatMsg from './BaseChatMsg.vue'
export default {
  name: 'ChatMsgImage',
  components: { BaseChatMsg },
  props: {
    avatar: String,
    url: String,
    align: {
      type: String,
      validator: value => {
        return ['left', 'right'].includes(value)
      }
    }
  },
  data() {
    return {
      loading: false,
      loaded: true,
      error: false,
      testUrl:
        'http://172.34.99.10:7001/public/chat_image/a583282bfa7549d197ed109613a3d0ae/a7055875666d47afbc42a77555ca2e6e.jpg'
    }
  },
  computed: {},
  created() {
    const { $Lazyload } = this
    if ($Lazyload) {
      $Lazyload.$on('loaded', this.onLazyLoaded)
      $Lazyload.$on('error', this.onLazyLoadError)
    }
  },
  beforeDestroy() {
    const { $Lazyload } = this
    if ($Lazyload) {
      $Lazyload.$off('loaded', this.onLazyLoaded)
      $Lazyload.$off('error', this.onLazyLoadError)
    }
  },
  methods: {
    loadImage() {
      const imageEle = this.$refs.image.$el.firstElementChild
      imageEle.setAttribute('preview', 'chat')
      this.$previewRefresh()
      this.$emit('load')
    },
    onLoad(event) {
      console.log('图片加载完毕------onload')
      this.loading = false
      this.loaded = true
      this.$emit('load', event)
    },

    onError(event) {
      this.error = true
      this.loading = false
      this.$emit('error', event)
    },

    onLazyLoaded({ el }) {
      if (el === this.$refs.image) {
        this.onLoad()
      }
    },

    onLazyLoadError({ el }) {
      if (el === this.$refs.image) {
        this.onError()
      }
    },

    onClick(event) {
      this.$emit('click', event)
    },
    revokeObjectURL() {
      if (this.type === 'image') {
        (window.URL || window.webkitURL).revokeObjectURL(this.url)
      }
    }
  }
}
</script>
<style lang="scss">
.image {
  .van-image__img {
    border-radius: 8px;
  }
}
</style>
<style lang="scss" scoped>
.image {
  min-width: 200px;
  min-height: 111px;
  max-width: 200px;
  max-height: 400px;
  .van-image__img {
    border-radius: 8px;
  }
  .loading {
    width: 100%;
    height: 100%;
    background-color: $gray-4;
  }
}
</style>
